<template>
    <el-dialog :title="dialogTitle" :visible.sync="currentDialogVisible" width="50%" @close="handleDialogClose">
        <el-form :model="ruleForm" :rules="editRules" ref="ruleForm" label-width="100px">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="头像" prop="name">
                        <el-upload class="avatar-uploader" :action="uploadUrl" :show-file-list="false"
                            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                            <img v-if="imageUrl" :src="imageUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>

                </el-col>
                <el-col :span="12">
                    <el-form-item label="民族" prop="nation">
                        <el-input v-model="ruleForm.nation" placeholder="请输入民族"></el-input>
                    </el-form-item>

                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="小区" prop="building">
                        <CasCader @handleChange="handleChange"></CasCader>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="籍贯" prop="usernative">
                        <el-input v-model="ruleForm.usernative" placeholder="请输入籍贯"></el-input>
                    </el-form-item>


                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="房间号" prop="room">
                        <el-input v-model="ruleForm.room" placeholder="请输入房间号"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="身份证号" prop="cardid">
                        <el-input v-model="ruleForm.cardid" placeholder="请输入身份证号"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="ruleForm.name" placeholder="请输入姓名"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="手机号" prop="mobile">
                        <el-input v-model="ruleForm.mobile" placeholder="请输入手机号"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">

                <el-col :span="12">
                    <el-form-item label="性别" prop="sex">
                        <el-radio-group v-model="ruleForm.sex" placeholder="请选择性别" style="width: 100%;">
                            <el-radio label="男"></el-radio>
                            <el-radio label="女"></el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="居民类型" prop="userType">
                        <el-select v-model="ruleForm.userType" placeholder="请选择居民类型" clearable>
                            <el-option v-for="item in userTypeOptions" :key="item.id" :label="item.name"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>

                </el-col>
            </el-row>
        </el-form>

        <span slot="footer" class="dialog-footer">
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handleSubmit()">确定</el-button>
        </span>
    </el-dialog>
</template>

<script>
import { add, update, userinfotype } from '../api/userinfo'
import CasCader from '../components/CasCader.vue';

export default {
    name: 'DialogUserinfo',
    components: {
        CasCader,
    },
    props: {
        dialogVisible: {
            type: Boolean,
            default: false
        },
        isEdit: {
            type: Boolean,
            default: false
        },
        editData: {
            type: Object,
            default: () => { }
        },
        // userTypeOptions: { 
        //     type: Array,
        //     default: () => []
        // }
    },
    data() {
        return {
            imageUrl: '',
            uploadUrl: process.env.VUE_APP_UPLOAD_API_URL,
            currentDialogVisible: this.dialogVisible,
            ruleForm: {
                id: null,
                name: '',
                sex: '',
                cardid: '',
                mobile: '',
                usernative: '',
                nation: '',
                building: '',
                room: '',
                userType: '',
                photo: ''
            },
            userTypeOptions: [],

            editRules: {
                name: [
                    { required: true, message: '请输入姓名', trigger: 'blur' }
                ],
                sex: [
                    { required: true, message: '请选择性别', trigger: 'change' }
                ],
                cardid: [
                    { required: true, message: '请输入身份证号', trigger: 'blur' }
                ],
                mobile: [
                    { required: true, message: '请输入手机号', trigger: 'blur' }
                ],
                building: [
                    { required: true, message: '请选择小区', trigger: 'change' }
                ],
                room: [
                    { required: true, message: '请输入房间号', trigger: 'blur' }
                ],
                userType: [
                    { required: true, message: '请选择居民类型', trigger: 'change' }
                ]
            },
        }
    },
    created() {
        this.getUserinfoTypeList();

    },


    computed: {
        dialogTitle() {
            return this.isEdit ? '修改居民信息' : '添加居民信息';
        }
    },

    watch: {
        dialogVisible(newVal) {
            this.currentDialogVisible = newVal;
            if (newVal) {
                if (this.isEdit) {
                    this.ruleForm = { ...this.editData };
                    // 编辑模式下设置头像显示
                    if (this.editData.photo) {
                        this.imageUrl = this.getFullImageUrl(this.editData.photo);
                    }
                } else {
                    this.resetruleForm();
                }
            }
        },

        currentDialogVisible(newVal) {
            if (!newVal) {
                this.$emit('handleCancel');
            }
        }
    },

    methods: {
        getFullImageUrl(url) {
            if (!url) return '';
            if (url.startsWith('http')) return url;
            return `${process.env.VUE_APP_UPLOAD_BASE_URL}${url}`;
        },
        
        async getUserinfoTypeList() {
            try {
                let { data: { list: listData } } = await userinfotype();
                console.log('获取到的居民类型:', listData);
                this.userTypeOptions = listData.map(item => {
                    return {
                        ...item,
                        id: parseInt(item.id)
                    };
                });
            } catch (error) {
                console.error('获取居民类型失败:', error);
                this.$message.error('获取居民类型失败');
            }
        },
        handleAvatarSuccess(res, file) {
            // 从上传响应中获取文件路径
            if (res && res.data) {
                this.ruleForm.photo = res.data;
                this.imageUrl = URL.createObjectURL(file.raw);
            } else {
                this.imageUrl = URL.createObjectURL(file.raw);
            }
        },


        handleChange(buildingarr) {
            this.ruleForm.building = buildingarr.length ? buildingarr[buildingarr.length - 1] : '';
        },
        handleDialogClose() {
            // 清除表单验证
            this.$refs.ruleForm.resetFields();
            // 手动移除焦点
            if (document.activeElement) {
                document.activeElement.blur();
            }

            this.$emit('handleCancel');
        },

        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        // 重置表单
        resetruleForm() {
            this.ruleForm = {
                id: null,
                name: '',
                sex: '',
                cardid: '',
                mobile: '',
                usernative: '',
                nation: '',
                building: '',
                room: '',
                userType: '',
                photo: ''
            };
            // 清理头像显示
            this.imageUrl = '';
        },
        // 取消操作
        handleCancel() {
            this.currentDialogVisible = false;
        },
        // 提交表单
        handleSubmit() {
            this.$refs.ruleForm.validate(async (valid) => {
                if (valid) {
                    try {
                        // 转换表单数据以匹配后端API要求
                        const submitData = {
                            ...this.ruleForm,
                            id: this.ruleForm.id || 0, // 确保id字段存在
                            sex: this.ruleForm.sex === '男' ? 1 : 2, // 将性别从字符串转换为数字
                            usertype: parseInt(this.ruleForm.userType) // 字段名从userType改为usertype
                        };
                        
                        // 删除不需要的字段
                        delete submitData.userType;

                        // 添加调试日志
                        console.log('提交的数据:', submitData);

                        if (this.isEdit) {
                            // 编辑模式
                            await update(submitData);
                            this.$message.success('更新成功');
                        } else {
                            // 新增模式
                            await add(submitData);
                            this.$message.success('添加成功');
                        }

                        this.currentDialogVisible = false;
                        this.$emit('refreshList');
                    } catch (error) {
                        console.error('保存失败:', error);
                        // 显示更详细的错误信息
                        if (error.response && error.response.data && error.response.data.message) {
                            this.$message.error(error.response.data.message);
                        } else {
                            this.$message.error(this.isEdit ? '更新失败' : '添加失败');
                        }
                    }
                } else {
                    console.log('表单验证失败!!');
                    this.$message.warning('请检查表单填写是否正确');
                    return false;
                }
            });
        }
    }
}
</script>

<style scoped>
/deep/.avatar-uploader .el-upload {
    border: 1px dashed #bababa;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 128px;
    height: 128px;
    line-height: 128px;
    text-align: center;
}

.avatar {
    width: 128px;
    height: 128px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    background-color: #e4e4e4;

    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
}

.avatar {
    width: 120px;
    height: 120px;
    display: block;
}
</style>